use actix_web::{post, web::{self, ServiceConfig}};
use serde::Deserialize;
use crate::{mcu::stm32::curd::{self, IpInfo, McuInfo, PinInfo, SignalInfo}, server::{req::Cbor, resp::{new_cbor, CborBody}}};

#[derive(Debug, Deserialize)]
struct QueryIpReq {
    mcu_id: i64,
}

#[post("/query/ip")]
async fn on_query_ip(req: Cbor<QueryIpReq>) -> CborBody<Vec<IpInfo>> {
    new_cbor( curd::query_ip(req.mcu_id).await? )
}

#[derive(Debug, Deserialize)]
struct QuerySignal {
    pin_id: i64,
}
#[post("/query/signal")]
async fn on_query_signal(req: Cbor<QuerySignal>) -> CborBody<Vec<SignalInfo>> {
    new_cbor( curd::query_signals(req.pin_id).await? )
}


#[derive(Debug, Deserialize)]
struct QueryPinReq {
    mcu_id: i64,
}

#[post("/query/pin")]
async fn on_query_pin(req: Cbor<QueryPinReq>) -> CborBody<Vec<PinInfo>> {
    let pins = curd::query_pin(req.mcu_id).await?;
    new_cbor(pins)
}

#[derive(Debug, Deserialize)]
struct QueryMcuReq {
    line: String
}

#[post("/query/mcu")]
async fn on_query_mcu(req: Cbor<QueryMcuReq>) -> CborBody<Vec<McuInfo>> {
    let mcus = curd::query_mcu(&req.line).await?;
    new_cbor(mcus)
}

#[post("/query/family")]
async fn on_query_family() -> CborBody<Vec<String>> {
    let familys = curd::query_family().await?;
    new_cbor(familys)
}

#[derive(Debug, Deserialize)]
struct QueryLineReq {
    family: String
}

#[post("/query/line")]
async fn on_query_line(req: Cbor<QueryLineReq>) -> CborBody<Vec<String>> {
    let lines = curd::query_line(&req.family).await?;
    new_cbor(lines)
}

pub fn register(cfg: &mut ServiceConfig) {
    let scope = web::scope("/mcu")
        .service(on_query_family)
        .service(on_query_line)
        .service(on_query_mcu)
        .service(on_query_pin)
        .service(on_query_signal)
        .service(on_query_ip)
        ;
    cfg.service(scope);
}

